package cn.itcast.netty.c1;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;

public class HelloServer {

    public static void main(String[] args) {
        //1. 启动器 负责组转netty组件，启动服务器
        new ServerBootstrap()
                // 2 Group：包含(BossEventLoop WorkerEventLoop)    EventLoop(一个selector+一个thread)
                .group(new NioEventLoopGroup())
                //3 选择一个ServerSocketChannel的实现
                .channel(NioServerSocketChannel.class)
                // 4 boss负责处理连接  worker负责处理读写,决定了worker能执行哪些操作（handler）
                .childHandler(
                        // 5 channel代表和客户端进行数据读写的通道,
                        // ChannelInitializer是一个特殊的handler,调用Initializer方法进行初始化，负责添加别的handler
                        new ChannelInitializer<NioSocketChannel>() {
                            @Override //连接建立后调用initChannel方法
                            protected void initChannel(NioSocketChannel ch) throws Exception {
                                //6 添加具体的handler ,接收事件后依次调用具体的handler
                                ch.pipeline().addLast(new StringDecoder()); //byteBuf -> String
                                ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {//自定义handler
                                    @Override //读事件
                                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//                                super.channelRead(ctx, msg);
                                        System.out.println(msg);
                                    }
                                });

                            }
                        })
                .bind(8080);//7 监听端口

    }
}
